package com.itheima.d1_reflect_constructor;

import org.junit.jupiter.api.Test;

import java.lang.reflect.Constructor;

/**
 * 反射获取构造器
 */
public class demo1 {
    /**
     * 1.getConstructors:
     *                  获取全部public的构造器
     */

    @Test
    public void getConstructors(){
        //1.获取类对象
        Class c = Student.class;

        //2.提取类中的构造器对象
        Constructor[] constructors = c.getConstructors();

        //3.遍历构造器
        for (Constructor constructor : constructors) {//getName:获取构造器名  getParameterCount: 获取构造器参数值
            System.out.println(constructor.getName()+"====>"+constructor.getParameterCount());
        }
    }


    /**
     * 2.getDeclareConstructors():
     *                  获取全部的构造器，需要获取权限(可以获取私有的)
     */
    @Test
    public void getDeclareConstructors(){
        //1.获取类对象
        Class c = Student.class;

        //2.提取类中的构造器对象
        Constructor[] constructors = c.getDeclaredConstructors();

        //3.遍历构造器
        for (Constructor constructor : constructors) {//getName:获取构造器名  getParameterCount: 获取构造器参数值
            System.out.println(constructor.getName()+"====>"+constructor.getParameterCount());
        }
    }

    /**
     * 3.getConstructor(Class... parameterTypes):
     *                  获取某个public的构造器
     *                  注意：参数类型应该和构造器的类型顺序一致才可以拿到
     */
    @Test
    public void getConstructor() throws NoSuchMethodException {
        //1.获取类对象
        Class c = Student.class;

        //2.提取类中的单个public构造器对象
        //Constructor constructor = c.getConstructor();

        //3.定位有参构造器
        Constructor constructor1 = c.getConstructor(String.class,int.class,String.class);
        //System.out.println(constructor.getName()+"====>"+constructor.getParameterCount());
        System.out.println(constructor1.getName()+"====>"+constructor1.getParameterCount());

    }

    /**
     * 4.getDeclareConstructor(Class... parameterTypes):
     *                  获取某个构造器
     */
    @Test
    public void getDeclareConstructor() throws NoSuchMethodException {
        //1.获取类对象
        Class c = Student.class;

        //2.无参
        Constructor constructor = c.getDeclaredConstructor();

        //3.有参
        Constructor constructor1 = c.getConstructor(String.class,int.class,String.class);

        System.out.println(constructor.getName()+"====>"+constructor.getParameterCount());
        System.out.println(constructor1.getName()+"====>"+constructor1.getParameterCount());


    }
}
